package Exercise;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ExerciseTransfer {
    public static void main(String[] args) throws InterruptedException {
        Account account1 = new Account();
        account1.setMoney(20000);

        Account account2 = new Account();
        account2.setMoney(20000);

        Random rand = new Random();

        List<Thread> threads = new ArrayList<Thread>();

        for(int i=0;i<2000;i++){

            Thread thread = new Thread(() -> {
                try {
                    Thread.sleep(rand.nextInt(10));
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                account1.transfer(account2, rand.nextInt() + 1);
            });
            thread.start();
        }
        for (Thread thread : threads) {
            thread.join();
        }
        log.info(String.valueOf(account1.getMoney()+account2.getMoney()));

    }
}

class  Account{
    private int money;

    public int getMoney() {
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }

    public void transfer(Account account, int amount) {
        synchronized (Account.class) {
            if(this.money >= amount) {
                this.money = this.money-amount;
                account.setMoney(account.getMoney()+amount);
            }
        }

    }
}
